package com.atiguigu.auth.controller;
 
import com.atiguigu.auth.service.SysMenuService;
import com.atiguigu.auth.service.SysUserService;
import com.atiguigu.common.config.exception.GuiguException;
import com.atiguigu.common.jwt.JwtHelper;
import com.atiguigu.common.result.Result;
import com.atiguigu.common.utils.MD5;
import com.atiguigu.model.system.SysUser;
import com.atiguigu.vo.system.LoginVo;
import com.atiguigu.vo.system.RouterVo;
import com.atiguigu.vo.wechat.MenuVo;
import io.jsonwebtoken.Jwt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.experimental.Helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台登录登出    前端guigu-oa-admin    src/api/user.js
 * </p>
 */
@Api(tags = "后台登录管理")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {
 
 
    /**
     * 登录
     * @return
     */

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @ApiOperation(value = "登录")
    @PostMapping("login")
    public Result login(@RequestBody LoginVo loginVo) {
        SysUser sysUser = sysUserService.getByUsername(loginVo.getUsername());
        //判断用户是否存在
        if(null == sysUser) {
            throw new GuiguException(201,"用户不存在");
        }

        if(!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
            throw new GuiguException(201,"密码错误");
        }
        if(sysUser.getStatus().intValue() == 0) {
            throw new GuiguException(201,"用户被禁用");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", JwtHelper.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);
    }
    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("info")
    public Result info(HttpServletRequest request) {
        String token = request.getHeader("token");
        String username = JwtHelper.getUsername(token);

        SysUser sysUser = sysUserService.getByUsername(username);
        List<RouterVo>  routerVoList = sysMenuService.findUserMenuListByUserId(sysUser.getId());

        List<String> permsList =sysMenuService.findUserPermsByUserId(sysUser.getId());

        Map<String, Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name",sysUser.getUsername());
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        map.put("routers",routerVoList);
        map.put("buttons",permsList);
        return Result.ok(map);
    }
    /**
     * 退出
     * @return
     */
    @PostMapping("logout")
    public Result logout(){
        return Result.ok();
    }
 
}